package model

import (
	"gorm.io/gorm"
	"smart-health-platforms/config"
	"time"
)

// 分销佣金记录表
type DistributionCommission struct {
	Id          uint32    `gorm:"column:id;type:int UNSIGNED;comment:分佣记录主键id;primaryKey;not null;" json:"id"`                  // 分佣记录主键id
	OrderSn     string    `gorm:"column:order_sn;type:varchar(50);comment:订单编号;not null;" json:"order_sn"`                      // 订单编号
	OrderAmount float64   `gorm:"column:order_amount;type:decimal(10, 2);comment:订单金额;not null;" json:"order_amount"`           // 订单金额
	UserId      uint32    `gorm:"column:user_id;type:int UNSIGNED;comment:来源用户id;not null;" json:"user_id"`                     // 来源用户id
	ToUserId    uint32    `gorm:"column:to_user_id;type:int UNSIGNED;comment:获得佣金id;not null;" json:"to_user_id"`               // 获得佣金id
	Amount      float64   `gorm:"column:amount;type:decimal(10, 2);comment:分销金额;not null;" json:"amount"`                       // 分销金额
	Level       uint32    `gorm:"column:level;type:int UNSIGNED;comment:分销用户等级：1一级 2二级;not null;" json:"level"`                 // 分销用户等级：1一级 2二级
	Status      uint32    `gorm:"column:status;type:int UNSIGNED;comment:状态: 0申请中 1已通过 2已拒绝;not null;default:1;" json:"status"` // 状态: 0申请中 1已通过 2已拒绝
	CreatedAt   time.Time `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	SettledAt   time.Time `gorm:"column:settled_at;type:datetime(3);default:NULL;" json:"settled_at"`
}

// 设置与数据库表的映射关系
func (dc *DistributionCommission) TableName() string {
	return "distribution_commission"
}

// 记录分销佣金
func (dc *DistributionCommission) BatchCreate(flows []*DistributionCommission) error {
	return config.DB.Create(&flows).Error
}

// 查询用户分销佣金流水
func (dc *DistributionCommission) GetUserDistributionCommissionList(userId uint32) (flows []*DistributionCommission, err error) {
	err = config.DB.Where("user_id = ?", userId).Find(&flows).Error
	return flows, nil
}

// 通过获得用户id查询用户分销佣金流水
func (dc *DistributionCommission) GetUserDistributionCommissionToUserId(tx *gorm.DB, userId uint32) error {
	return config.DB.Where("to_user_id = ?", userId).Limit(1).Find(&dc).Error
}

// 根据订单号查询分销佣金
func (dc *DistributionCommission) GetDistributionCommissionByOrderSn(tx *gorm.DB, orderSn string) (flows []*DistributionCommission, err error) {
	err = config.DB.Where("order_sn = ?", orderSn).Find(&flows).Error
	return flows, nil
}
